import axios from 'axios'
import Utils from '../common/utils.js'
import { message } from 'antd';
import { prefix } from '../common/globalStyle'
// let location = window.location
process.env.NODE_ENV === 'production' ? axios.defaults.baseURL = prefix : axios.defaults.baseURL=""

const service = function (url, data, method = 'GET', headers = {}) {
  return new Promise((resolve, reject) => {
    let options = {
      'method': method,
      'url': url,
      'headers': headers && typeof headers === 'object' ? headers : {}
    }
    options[method === 'GET' ? 'params' : 'data'] = data
    axios.defaults.withCredentials = true

    axios(options).then((response) => {
      if(response.data.code === 20000) {
        resolve(response.data)
      } else {
        debugger
        if(response.data.code === 30003 || response.data.code === 4201) {
          localStorage.clear()
          sessionStorage.clear()
          window.location.href="/"
          message.error(response.data.msg)
          setTimeout(()=> {
            if(GetUrlRelativePath() !== '/') {
              window.location.href="/"
            }
          }, 2000)
        }else if(response.data.code === 5006) {
          resolve(response.data)
          return 
        }else if(response.data.code === 5009) {
          message.error(response.data.msg)
          setTimeout(()=> {
            window.location.href="/"
          },2000)
        }
        message.error(response.data.msg)
      }
      
    }).catch((error) => {
      reject(error)
    })
  })
}


function GetUrlRelativePath(){
　var url = document.location.toString();
　var arrUrl = url.split("//");
　var start = arrUrl[1].indexOf("/");
　var relUrl = arrUrl[1].substring(start);//stop省略，截取从start开始到结尾的所有字符

　if(relUrl.indexOf("?") != -1){
　　relUrl = relUrl.split("?")[0];
　}
　return relUrl;
}
export default service
